#include "SOFT_PWM.h"

volatile Typedef_PWM PWM_Ctrl;
uint8 DestPwmDuty[6];
uint8 CntUpdateTm,TmPwmChange;

void initSoftPWM(void)
{
    uint8 i;

    PWM_Ctrl.Step = 0;

    for(i=0; i<6; i++)
    {
        PWM_Ctrl.Duty[i] = 0;
        DestPwmDuty[i] = 0;
    }
    CntUpdateTm = 0;
    TmPwmChange = 1;
}

void SoftPwmCore(void)
{
    PWM_Ctrl.Step++;
    if(PWM_Ctrl.Step >= MAX_PWM_STEP)
    {
        PWM_Ctrl.Step = 0;
        if(PWM_Ctrl.Duty[0])     P_PWM1 = 0;
        else                     P_PWM1 = 1;
        if(PWM_Ctrl.Duty[1])     P_PWM2 = 0;
        else                     P_PWM2 = 1;
        if(PWM_Ctrl.Duty[2])     P_PWM3 = 0;
        else                     P_PWM3 = 1;
        if(PWM_Ctrl.Duty[3])     P_PWM4 = 0;
        else                     P_PWM4 = 1;
        if(PWM_Ctrl.Duty[4])     P_PWM5 = 0;
        else                     P_PWM5 = 1;
        if(PWM_Ctrl.Duty[5])     P_PWM6 = 0;
        else                     P_PWM6 = 1;
    }
    else
    {
        if(PWM_Ctrl.Duty[0])
        {
            if(PWM_Ctrl.Step >= PWM_Ctrl.Duty[0])      P_PWM1 = 1;
        }
        else
        {
            P_PWM1 = 1;
        }

        if(PWM_Ctrl.Duty[1])
        {
            if(PWM_Ctrl.Step >= PWM_Ctrl.Duty[1])      P_PWM2 = 1;
        }
        else
        {
            P_PWM2 = 1;
        }
        if(PWM_Ctrl.Duty[2])
        {
            if(PWM_Ctrl.Step >= PWM_Ctrl.Duty[2])      P_PWM3 = 1;
        }
        else
        {
            P_PWM3 = 1;
        }
        if(PWM_Ctrl.Duty[3])
        {
            if(PWM_Ctrl.Step >= PWM_Ctrl.Duty[3])      P_PWM4 = 1;
        }
        else
        {
            P_PWM4 = 1;
        }
        if(PWM_Ctrl.Duty[4])
        {
            if(PWM_Ctrl.Step >= PWM_Ctrl.Duty[4])      P_PWM5 = 1;
        }
        else
        {
            P_PWM5 = 1;
        }
        if(PWM_Ctrl.Duty[5])
        {
            if(PWM_Ctrl.Step >= PWM_Ctrl.Duty[5])      P_PWM6 = 1;
        }
        else
        {
            P_PWM6 = 1;
        }
    }

}


void SoftPwm_UpdateDuty(void)
{
    uint8 i;

    if(TmPwmChange)
    {
        CntUpdateTm++;
        if(CntUpdateTm >= TmPwmChange)
        {
            CntUpdateTm = 0;

            for(i=0; i<6; i++)
            {
                if(PWM_Ctrl.Duty[i] > DestPwmDuty[i])      PWM_Ctrl.Duty[i]--;
                else if(PWM_Ctrl.Duty[i] < DestPwmDuty[i])  PWM_Ctrl.Duty[i]++;
            }
        }
    }
    else
    {
        for(i=0; i<6; i++)
        {
            PWM_Ctrl.Duty[i] = DestPwmDuty[i];
        }
    }
}